<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>01-computed</title>
</head>
<body>
<div id="app">
    <table>
        <thead>
            <tr>
                <th>编号</th>
                <th>书名</th>
                <th>价格</th>
                <th>库存</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="book in books">
                <th>{{book.id}}</th>
                <th>{{book.name}}</th>
                <th>{{book.price}}</th>
                <th><input type="number" v-model="book.num"/></th>
            </tr>
        </tbody>
    </table>
    <div>总价：￥{{totalPrice}}</div>
    <div style="color: red">{{msg}}</div>
</div>
<script src="../node_modules/vue/dist/vue.min.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            "books": [
                {"id": 1, name: "西游记", price: 98.88, num: 1},
                {"id": 2, name: "三国演义", price: 98, num: 2},
                {"id": 3, name: "红楼梦", price: 100, num: 2},
            ],
            "msg": ""
        },
        computed: {
            totalPrice() {
                return  this.books.reduce((accumulator, currentValue, currentIndex, array) => {
                    //console.log("已累计" + accumulator);
                    let currentPrice = currentValue.price * currentValue.num;
                    //console.log(currentValue.name + "的总价为：" + currentPrice);
                    return accumulator + currentPrice;
                }, 0);
            },
            computedBooksNum() {
                return {"1": Number(this.books[0].num), "2": Number(this.books[1].num), "3": Number(this.books[2].num)}
            }
        },
        watch: {
            computedBooksNum: {
                handler(newVal, oldVal) {
                    let showMsg = false;
                    for (let i = 1; i <= 3; i++) {
                        if (newVal[i] <= 0) {
                            showMsg = true;
                            this.books[i - 1].num = 0;
                        }
                    }
                    if (showMsg) {
                        this.msg = "库存不能小于0";
                    } else {
                        this.msg = "";
                    }
                },
                deep: true
            }
        }

    });
</script>
</body>
</html>